from rest_framework import serializers
from .models import Comment, Like


class CommentSerializer(serializers.ModelSerializer):
    """评论序列化器"""
    author_name = serializers.CharField(source='author.name', read_only=True)
    author_id = serializers.IntegerField(source='author.id', read_only=True)
    author_avatar = serializers.SerializerMethodField()
    is_liked = serializers.SerializerMethodField()
    
    class Meta:
        model = Comment
        fields = [
            'id', 'author_name', 'author_id', 'author_avatar',
            'content', 'likes', 'is_liked', 'created_at'
        ]
        read_only_fields = ['id', 'likes', 'created_at']
    
    def get_author_avatar(self, obj):
        """获取作者头像URL"""
        if obj.author.avatar:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.author.avatar.url)
            return obj.author.avatar.url
        return '/media/avatars/default.png'
    
    def get_is_liked(self, obj):
        """当前用户是否已点赞该评论"""
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            return Like.objects.filter(user=request.user, comment=obj).exists()
        return False


class CommentCreateSerializer(serializers.ModelSerializer):
    """评论创建序列化器"""
    class Meta:
        model = Comment
        fields = ['content']
    
    def validate_content(self, value):
        """验证评论内容"""
        if not value or not value.strip():
            raise serializers.ValidationError('评论内容不能为空')
        if len(value) > 500:
            raise serializers.ValidationError('评论内容不能超过500字')
        return value.strip()
